package com.fengke.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.fengke.dao.product.ProductManager;
import com.fengke.dao.sn.SnManager;
import com.fengke.dao.admin.AdminManager;
import com.fengke.dao.member.MemberManager;
import com.fengke.dao.model.DepartureModel;
import com.fengke.dao.model.DestinationModel;
import com.fengke.dao.model.MemberModel;
import com.fengke.dao.model.PriceItemModel;
import com.fengke.dao.model.ProductImageModel;
import com.fengke.dao.model.ProductItemModel;
import com.fengke.dao.model.ProductModel;
import com.fengke.dao.model.ProductCategoryModel;
import com.fengke.dao.model.ProductTagModel;
import com.fengke.dao.model.Sn.Type;
import com.fengke.service.ProductService;
import com.fengke.service.vo.DepartureVO;
import com.fengke.service.vo.DestinationVO;
import com.fengke.service.vo.ProductVO;
import com.fengke.service.vo.ProductCategoryVO;
import com.fengke.util.DateUtil;
import com.fengke.util.StringUtil;
import com.fengke.util.file.FileUtil;
import com.fengke.util.file.UploadedFile;
import com.fengke.util.system.SystemConfig;

public class ProductServiceImpl implements ProductService {
	private ProductManager productManager;
	private SnManager snManager;
	private MemberManager memberManager;
	private AdminManager adminManager;

	public Integer researchProductListSize(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null) {
			productVO.setProductModel(new ProductModel());
		}
		return productManager.researchProductListSize(productVO.getProductModel());
	}
	public List<ProductVO> researchProductList(ProductVO productVO, int offset, int limit) throws Exception {
		if(productVO.getProductModel() == null) {
			productVO.setProductModel(new ProductModel());
		}
		List<ProductModel> productModelList = productManager.researchProductList(productVO.getProductModel(), offset, limit);
		if(productModelList != null && productModelList.size() > 0) {
			List<ProductVO> productVOList = new ArrayList<ProductVO> ();
			for(ProductModel model : productModelList) {
				ProductVO vo = new ProductVO();
				vo.setProductModel(model);
				// 标签
				ProductTagModel productTagModel = new ProductTagModel();
				productTagModel.setProductModel(model);
				List<ProductTagModel> productTagList = productManager.researchProductTagListByProductId(productTagModel);
				if(productTagList != null && productTagList.size() > 0) {
					vo.setProductTags(productTagList);
				}
				productVOList.add(vo);
			}
			return productVOList;
		}
		return null;
	}
	
	public int deleteProductByIds(List<String> idList) throws Exception {
		if(idList == null || idList.size() <= 0) {
			return 0;
		}
		// 级联删除 行程、故事
		productManager.deleteProductItemByProductIds(idList);
		productManager.deleteAdminStoryByProductIds(idList);
		// 级联删除图片
		productManager.deleteProductImageByProductIds(idList);
		// 删除标签
		productManager.deleteProductTagByProductIds(idList);
		
		return productManager.deleteProductByIds(idList);
	}
	@Override
	public int marketableProductByIds(Map<String, Object> paramMap) throws Exception {
		if(paramMap == null || paramMap.size() <= 0) {
			return 0;
		}
		return productManager.marketableProductByIds(paramMap);
	}
	public Object createProduct(ProductVO productVO) throws Exception {
		if(productVO == null || productVO.getProductModel() == null) {
			return null;
		}
		productVO.getProductModel().setSn(snManager.generate(Type.product));
		productVO.getProductModel().setCreateDate(new Date());
		productVO.getProductModel().setModifyDate(new Date());
		
		// 处理productimage
		productVO.getProductModel().setImage(FileUtil.uploadImageFile(productVO.getHeadImage()));
		
		if(productVO.getProductModel().getIsTop() != null && productVO.getProductModel().getIsTop()) {
			productVO.getProductModel().setStickTime(new Date());
		}
		String maxDateStr = productVO.getProductModel().getMaxDateStr();
		if(!StringUtil.isEmpty(maxDateStr)) {
			productVO.getProductModel().setExpire(DateUtil.parseDate(maxDateStr));
		}
		
		if(productVO.getProductModel().getMarketPrice() == null) {
			productVO.getProductModel().setMarketPrice(calculateDefaultMarketPrice(productVO.getProductModel().getPrice()));
		}
		
		if(productVO.getProductModel().getPoint() == null) {
			productVO.getProductModel().setPoint(calculateDefaultPoint(productVO.getProductModel().getPrice()));
		}

		productVO.getProductModel().setName(productVO.getProductModel().getFullName());
		productVO.getProductModel().setAllocatedStock(0);
		productVO.getProductModel().setSales(0L);
		productVO.getProductModel().setIsGift(false);
		productVO.getProductModel().setIsList(false);
		productVO.getProductModel().setPoint(productVO.getProductModel().getPrice().longValue());
		productVO.getProductModel().setIsPCShow(false);
		productVO.getProductModel().setIsCarousel(false);
		
		if(productVO.getProductModel().getHoursePrice() == null) {
			productVO.getProductModel().setHoursePrice(new BigDecimal(0));
		}
		if(productVO.getProductModel().getChildrenPrice() == null) {
			productVO.getProductModel().setChildrenPrice(new BigDecimal(0));
		}
		
		long productId = (Long) productManager.createProduct(productVO.getProductModel());
		productVO.getProductModel().setId(productId);
		// 行程
		if(productVO.getProductItems() != null && productVO.getProductItems().size() > 0) {
			for(int i = 0; i < productVO.getProductItems().size(); i ++) {
				ProductItemModel itemModel = productVO.getProductItems().get(i);
				if(itemModel != null) {
					itemModel.setProductModel(productVO.getProductModel());
					itemModel.setCreateDate(new Date());
					itemModel.setModifyDate(new Date());
					itemModel.setId((Long)productManager.createProductItem(itemModel));
				}
			}
		}
		// 档位列表
		if(productVO.getPriceItemModels() != null && productVO.getPriceItemModels().size() > 0) {
			for(int i = 0; i < productVO.getPriceItemModels().size(); i ++) {
				PriceItemModel itemModel = productVO.getPriceItemModels().get(i);
				if(itemModel != null) {
					itemModel.setProductModel(productVO.getProductModel());
					itemModel.setCreateDate(new Date());
					itemModel.setModifyDate(new Date());
					itemModel.setId(productManager.createPriceItem(itemModel));
				}
			}
		}
		
		// 商家故事
//		if(productVO.getAdminStorys() != null && productVO.getAdminStorys().size() > 0) {
//			for(AdminStoryModel story : productVO.getAdminStorys()) {
//				story.setProductModel(productVO.getProductModel());
//				story.setCreateDate(new Date());
//				story.setModifyDate(new Date());
//				if(!StringUtil.isEmpty(story.getContent())) {
//					story.setContent1(story.getContent().replaceAll("src=", "data-original="));
//				}
//				story.setId((Long)productManager.createAdminStory(story));
//			}
//		}
		// 轮播图片
		if(productVO.getProductImages() != null && productVO.getProductItems().size() > 0) {
			for(UploadedFile imageFile : productVO.getProductImages()) {
				ProductImageModel productImageModel = new ProductImageModel();
				productImageModel.setProductModel(productVO.getProductModel());
				productImageModel.setSource(FileUtil.uploadImageFile(imageFile));
				productManager.createProductImage(productImageModel);
			}
		}
		// 产品标签
		if(productVO.getProductTags() != null && productVO.getProductTags().size() > 0) {
			for(int i = 0; i < productVO.getProductTags().size(); i ++) {
				ProductTagModel productTagModel = productVO.getProductTags().get(i);
				if(productTagModel != null && productTagModel.getTagModel() != null && productTagModel.getTagModel().getId() != null) {
					productTagModel.setProductModel(new ProductModel());
					productTagModel.getProductModel().setId(productVO.getProductModel().getId());
					productManager.createProductTag(productTagModel);
				}
			}
		}
		return productId;
	}
	public ProductVO researchProductById(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null || (productVO.getProductModel().getId() == null && productVO.getProductModel().getSn() == null)) {
			return null;
		}
		ProductModel model = productManager.researchProductById(productVO.getProductModel());
		productVO.setProductModel(model);
		// 商家信息
		if(model != null && model.getAdminModel() != null && model.getAdminModel().getId() != null) {
			model.setAdminModel(adminManager.researchAdminById(model.getAdminModel()));
		}
		// 行程
		ProductItemModel productItemModel = new ProductItemModel();
		productItemModel.setProductModel(model);
		List<ProductItemModel> productItemModelList = productManager.researchProductItemList(productItemModel);
		if(productItemModelList != null && productItemModelList.size() > 0) {
			productVO.setProductItems(productItemModelList);
		}
		// 档位信息
		PriceItemModel priceItemModel = new PriceItemModel();
		priceItemModel.setProductModel(model);
		List<PriceItemModel> priceItemModelList = productManager.researchPriceItemList(priceItemModel);
		if(priceItemModelList != null && priceItemModelList.size() > 0) {
			productVO.setPriceItemModels(priceItemModelList);
		}
		// 商家故事
//		AdminStoryModel adminStoryModel = new AdminStoryModel();
//		adminStoryModel.setProductModel(model);
//		List<AdminStoryModel> adminStoryModelList = productManager.researchAdminStoryList(adminStoryModel);
//		if(adminStoryModelList != null && adminStoryModelList.size() > 0) {
//			productVO.setAdminStorys(adminStoryModelList);
//		}
		// 轮播图片
		ProductImageModel productImageModel = new ProductImageModel();
		productImageModel.setProductModel(model);
		List<ProductImageModel> productImageModelList = productManager.researchProductImageList(productImageModel);
		if(productImageModelList != null && productImageModelList.size() > 0) {
			productVO.setProductImageModels(productImageModelList);
		}
		// 参加该商品的会员
		List<MemberModel> memberModelList = memberManager.researchMemberListByProductInfo(productVO.getProductModel());
		if(memberModelList != null && memberModelList.size() > 0) {
			productVO.setMembers(memberModelList);
		}
		// 标签
		ProductTagModel productTagModel = new ProductTagModel();
		productTagModel.setProductModel(model);
		List<ProductTagModel> productTagList = productManager.researchProductTagListByProductId(productTagModel);
		if(productTagList != null && productTagList.size() > 0) {
			productVO.setProductTags(productTagList);
		}
		
		return productVO;
	}
	public int updateProductById(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null || productVO.getProductModel().getId() == null) {
			return 0;
		}
		List<String> idList = new ArrayList<String>();
		idList.add(String.valueOf(productVO.getProductModel().getId()));
		// 行程
		if(productVO.getProductItems() != null && productVO.getProductItems().size() > 0) {
			// 先删除，然后添加所有
			productManager.deleteProductItemByProductIds(idList);
			for(int i = 0; i < productVO.getProductItems().size(); i ++) {
				ProductItemModel itemModel = productVO.getProductItems().get(i);
				if(itemModel != null) {
					itemModel.setProductModel(productVO.getProductModel());
					itemModel.setCreateDate(new Date());
					itemModel.setModifyDate(new Date());
					itemModel.setId((Long)productManager.createProductItem(itemModel));
				}
			}
		}
		
		// 档位列表
		if(productVO.getPriceItemModels() != null && productVO.getPriceItemModels().size() > 0) {
			// 先删除，然后添加所有
			productManager.deletePriceItemByProductIds(idList);
			for(int i = 0; i < productVO.getPriceItemModels().size(); i ++) {
				PriceItemModel itemModel = productVO.getPriceItemModels().get(i);
				if(itemModel != null) {
					itemModel.setProductModel(productVO.getProductModel());
					itemModel.setCreateDate(new Date());
					itemModel.setModifyDate(new Date());
					itemModel.setId(productManager.createPriceItem(itemModel));
				}
			}
		}
		
		// 商家故事
//		if(productVO.getAdminStorys() != null && productVO.getAdminStorys().size() > 0) {
//			for(AdminStoryModel story : productVO.getAdminStorys()) {
//				if(story.getId() != null) {
//					story.setModifyDate(new Date());
//					productManager.updateAdminStoryById(story);
//				} else {
//					story.setCreateDate(new Date());
//					story.setModifyDate(new Date());
//					story.setId((Long)productManager.createAdminStory(story));
//				}
//			}
//		}
		// 轮播图片
		if(productVO.getProductImages() != null && productVO.getProductImages().size() > 0) {
			// 先删除原有
			productManager.deleteProductImageByProductIds(idList);
			// 再插入
			for(int i = 0; i < productVO.getProductImages().size(); i ++) {
				if(productVO.getProductImages().get(i) != null) {
					ProductImageModel productImageModel = new ProductImageModel();
					productImageModel.setProductModel(productVO.getProductModel());
					productImageModel.setSource(FileUtil.uploadImageFile(productVO.getProductImages().get(i)));
					productManager.createProductImage(productImageModel);
				}
			}
		}
		// 产品标签
		if(productVO.getProductTags() != null && productVO.getProductTags().size() > 0) {
			// 先删除原有
			productManager.deleteProductTagByProductIds(idList);
			// 再插入
			for(int i = 0; i < productVO.getProductTags().size(); i ++) {
				ProductTagModel productTagModel = productVO.getProductTags().get(i);
				if(productTagModel != null && productTagModel.getTagModel() != null && productTagModel.getTagModel().getId() != null) {
					productTagModel.setProductModel(productVO.getProductModel());
					productManager.createProductTag(productTagModel);
				}
			}
		}
		productVO.getProductModel().setSn(snManager.generate(Type.product));
		productVO.getProductModel().setCreateDate(new Date());
		productVO.getProductModel().setModifyDate(new Date());
		productVO.getProductModel().setIsGift(false);
		productVO.getProductModel().setIsList(false);
		productVO.getProductModel().setIsPCShow(false);
		productVO.getProductModel().setIsCarousel(false);
		productVO.getProductModel().setName(productVO.getProductModel().getFullName());
		productVO.getProductModel().setPoint(productVO.getProductModel().getPrice().longValue());
		productVO.getProductModel().setSales(0L);
		productVO.getProductModel().setAllocatedStock(0);
		
		if(productVO.getProductModel().getIsTop() != null && productVO.getProductModel().getIsTop()) {
			productVO.getProductModel().setStickTime(new Date());
		}
		
		String maxDateStr = productVO.getProductModel().getMaxDateStr();
		if(!StringUtil.isEmpty(maxDateStr)) {
			productVO.getProductModel().setExpire(DateUtil.parseDate(maxDateStr));
		}
		
		if(productVO.getProductModel().getMarketPrice() == null) {
			productVO.getProductModel().setMarketPrice(calculateDefaultMarketPrice(productVO.getProductModel().getPrice()));
		}
		
		if(productVO.getProductModel().getPoint() == null) {
			productVO.getProductModel().setPoint(calculateDefaultPoint(productVO.getProductModel().getPrice()));
		}

		if(productVO.getProductModel().getHoursePrice() == null) {
			productVO.getProductModel().setHoursePrice(new BigDecimal(0));
		}
		if(productVO.getProductModel().getChildrenPrice() == null) {
			productVO.getProductModel().setChildrenPrice(new BigDecimal(0));
		}
		
		if(productVO.getHeadImage() != null && !StringUtil.isEmpty(productVO.getHeadImage().getFileName())) {
			productVO.getProductModel().setImage(FileUtil.uploadImageFile(productVO.getHeadImage()));
		}
		return productManager.updateProductById(productVO.getProductModel());
	}
	public List<ProductCategoryVO> researchProductCategoryList(ProductCategoryVO productCategoryVO, int offset, int limit) throws Exception {
		if(productCategoryVO.getProductCategoryModel() == null) {
			productCategoryVO.setProductCategoryModel(new ProductCategoryModel());
		}
		List<ProductCategoryModel> typeList = productManager.researchProductCategoryList(productCategoryVO.getProductCategoryModel(), offset, limit);
		if(typeList != null && typeList.size() > 0) {
			List<ProductCategoryVO> typeVOList = new ArrayList<ProductCategoryVO>();
			for(ProductCategoryModel type : typeList) {
				ProductCategoryVO typeVO = new ProductCategoryVO();
				typeVO.setProductCategoryModel(type);;
				typeVOList.add(typeVO);
			}
			return typeVOList;
		}
		return null;
	}

	@Override
	public List<ProductCategoryVO> researchProductCategoryListByOnlineProduct(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null) {
			productVO.setProductModel(new ProductModel());
		}
		List<ProductCategoryModel> typeList = productManager.researchProductCategoryListByOnlineProduct(productVO.getProductModel());
		if(typeList != null && typeList.size() > 0) {
			List<ProductCategoryVO> typeVOList = new ArrayList<ProductCategoryVO>();
			for(ProductCategoryModel type : typeList) {
				ProductCategoryVO typeVO = new ProductCategoryVO();
				typeVO.setProductCategoryModel(type);;
				typeVOList.add(typeVO);
			}
			return typeVOList;
		}
		return null;
	}
	
	@Override
	public ProductCategoryVO createProductCategory(ProductCategoryVO productCategoryVO) throws Exception {
		productCategoryVO.getProductCategoryModel().setId(productManager.createProductCategory(productCategoryVO.getProductCategoryModel()));
		return productCategoryVO;
	}
	@Override
	public ProductCategoryVO updateProductCategoryById(ProductCategoryVO productCategoryVO) throws Exception {
		productManager.updateProductCategoryById(productCategoryVO.getProductCategoryModel());
		return productCategoryVO;
	}
	@Override
	public void deleteProductCategoryByIds(List<String> list) throws Exception {
		productManager.deleteProductCategoryByIds(list);
	}
	@Override
	public List<DepartureVO> researchDepartureVOListByOnlineProduct(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null) {
			productVO.setProductModel(new ProductModel());
		}
		List<DepartureModel> departureModelList = productManager.researchDepartureListByOnlineProduct(productVO.getProductModel());
		if(departureModelList != null && departureModelList.size() > 0) {
			List<DepartureVO> voList = new ArrayList<DepartureVO>();
			for(DepartureModel model : departureModelList) {
				DepartureVO vo = new DepartureVO();
				vo.setDepartureModel(model);
				voList.add(vo);
			}
			return voList;
		}
		return null;
	}
	@Override
	public List<DestinationVO> researchDestinationVOListByOnlineProduct(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null) {
			productVO.setProductModel(new ProductModel());
		}
		List<DestinationModel> destinationModelList = productManager.researchDestinationListByOnlineProduct(productVO.getProductModel());
		if(destinationModelList != null && destinationModelList.size() > 0) {
			List<DestinationVO> voList = new ArrayList<DestinationVO>();
			for(DestinationModel model : destinationModelList) {
				DestinationVO vo = new DestinationVO();
				vo.setDestinationModel(model);
				voList.add(vo);
			}
			return voList;
		}
		return null;
	}
	@Override
	public List<String> researchStartDateListByOnlineProduct(ProductVO productVO) throws Exception {
		if(productVO.getProductModel() == null) {
			productVO.setProductModel(new ProductModel());
		}
		return productManager.researchStartDateListByOnlineProduct(productVO.getProductModel());
	}
	public ProductManager getProductManager() {
		return productManager;
	}
	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}
	public SnManager getSnManager() {
		return snManager;
	}
	public void setSnManager(SnManager snManager) {
		this.snManager = snManager;
	}
	/**
	 * 计算默认市场价
	 * 
	 * @param price
	 *            价格
	 */
	private BigDecimal calculateDefaultMarketPrice(BigDecimal price) {
		SystemConfig setting = SystemConfig.getInstance();
		Double defaultMarketPriceScale = setting.getDefaultMarketPriceScale();
		return setting.setScale(price.multiply(new BigDecimal(
				defaultMarketPriceScale.toString())));
	}

	/**
	 * 计算默认积分
	 * 
	 * @param price
	 *            价格
	 */
	private long calculateDefaultPoint(BigDecimal price) {
		SystemConfig setting = SystemConfig.getInstance();
		Double defaultPointScale = setting.getDefaultPointScale();
		return price.multiply(new BigDecimal(defaultPointScale.toString()))
				.longValue();
	}
	public MemberManager getMemberManager() {
		return memberManager;
	}
	public void setMemberManager(MemberManager memberManager) {
		this.memberManager = memberManager;
	}
	public AdminManager getAdminManager() {
		return adminManager;
	}
	public void setAdminManager(AdminManager adminManager) {
		this.adminManager = adminManager;
	}
}
